<template>
  <view class="customize-travel">
    <!-- AI对话区域 -->
    <view class="chat-section">
      <textarea class="chat-input" v-model="userInput" placeholder="请输入您想去的地方和旅行偏好，例如：我想去杭州玩3天，喜欢文艺小资的地方..."
        :maxlength="500" @confirm="generatePlan"></textarea>
      <button class="send-btn" @click="generatePlan" :disabled="loading">
        <text class="icon">🚀</text>
        <text>{{ loading ? '生成中...' : '生成攻略' }}</text>
      </button>
    </view>

    <!-- 加载动画 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-content">
        <view class="loading-spinner">
          <view class="spinner-circle"></view>
          <view class="spinner-circle"></view>
          <view class="spinner-circle"></view>
        </view>
        <view class="loading-text">
          <text class="title">AI正在为您规划行程</text>
          <text class="subtitle">{{ loadingTips[currentTipIndex] }}</text>
        </view>
      </view>
    </view>

    <!-- 攻略展示区域 -->
    <scroll-view v-else-if="travelPlan" class="plan-section" scroll-y>
      <view class="plan-content">
        <view class="plan-title">🎯 为您定制的行程</view>
        <rich-text :nodes="formattedPlan"></rich-text>
      </view>
    </scroll-view>

    <!-- 底部按钮区域 -->
    <view class="bottom-buttons" v-if="travelPlan">
      <button class="route-map-btn" @click="viewRouteMap">
        <text class="icon">🗺️</text>
        <text>查看路线轨迹</text>
      </button>
      <button class="save-plan-btn" @click="saveToPlan">
        <text class="icon">💾</text>
        <text>保存为行程</text>
      </button>
    </view>
  </view>
</template>

<script>
import { getAiResponse } from '@/api/ai';
import { getLastLocation } from '@/api/location';
import { getIpLocation } from '@/api/GaoDeApi';
import { getUserTravelPlans, createTravelPlan, updateTravelPlan } from '@/api/plan';

export default {
  data() {
    return {
      userInput: '',
      travelPlan: '',
      loading: false,
      error: '',
      currentTipIndex: 0,
      loadingTips: [
        '正在分析您的旅行偏好...',
        '正在规划最佳行程路线...',
        '正在优化景点游览顺序...',
        '正在添加特色美食推荐...',
        '正在完善交通建议...',
        '马上就好...'
      ],
      tipTimer: null,
      currentCity: null,
      weatherData: null,
      messageCache: {},
      formattedTitle: '',
      formattedDate: '',
      formattedWeather: [],
      formattedTips: '',
      formattedSchedule: []
    }
  },
  computed: {
    formattedPlan() {
      if (!this.travelPlan) return '';
      return this.formatRecommendContent(this.travelPlan);
    }
  },
  methods: {
    // 格式化推荐内容
    formatRecommendContent(text) {
      try {
        // 重置格式化数据
        this.formattedTitle = '';
        this.formattedDate = '';
        this.formattedWeather = [];
        this.formattedTips = '';
        this.formattedSchedule = [];

        // 清理文本中的所有**符号
        text = text.replace(/\*\*/g, '');

        // 提取并处理行程安排
        const scheduleMatches = text.matchAll(/第([一二三四五六七八九十\d]+)[天日][\s\S]*?(?=第[一二三四五六七八九十\d]+[天日]|$)/g);
        const schedules = Array.from(scheduleMatches);

        schedules.forEach((match) => {
          const dayContent = match[0];
          const dayNumber = match[1];
          const dayTitle = `第${dayNumber}天`;

          const timeSlots = [];
          const timeMatches = dayContent.matchAll(/([上中下晚]午|早晨|傍晚|晚上)[:：]([\s\S]*?)(?=[上中下晚]午|早晨|傍晚|晚上|$)/g);

          for (const timeMatch of timeMatches) {
            const timeSlot = timeMatch[1];
            const activities = timeMatch[2].trim()
              .split(/\d+[\.。、]/)
              .filter(activity => activity.trim())
              .map(activity => activity.trim());

            activities.forEach(activity => {
              if (activity) {
                timeSlots.push({
                  time: timeSlot,
                  activity: activity
                });
              }
            });
          }

          if (timeSlots.length > 0) {
            this.formattedSchedule.push({
              title: dayTitle,
              slots: timeSlots
            });
          }
        });

        // 将格式化后的内容转换为HTML
        return text
          .replace(/\n/g, '<br>')
          .replace(/第([一二三四五六七八九十\d]+)[天日]/g, '<strong style="color: #4CAF50">第$1天</strong>')
          .replace(/([上中下晚]午|早晨|傍晚|晚上)[:：]/g, '<strong style="color: #2196F3">$1：</strong>');
      } catch (err) {
        console.error('格式化推荐内容失败:', err);
        return text;
      }
    },

    // 构建AI请求消息
    buildRequestMessage() {
      if (!this.userInput.trim()) return null;

      let message = this.userInput;

      // 如果没有明确指定天数，尝试从输入中提取或使用默认值
      if (!message.includes('天') && !message.includes('日')) {
        message += '，请帮我规划2天的行程';
      }

      // 添加具体要求
      message += '，请帮我生成一份详细的旅游攻略，包含每天的具体行程安排，每天的行程要包含景点的游玩时间，并注意合理安排游玩顺序和时间。';

      return message;
    },

    // 开始加载动画
    startLoadingAnimation() {
      this.currentTipIndex = 0;
      this.tipTimer = setInterval(() => {
        this.currentTipIndex = (this.currentTipIndex + 1) % this.loadingTips.length;
      }, 2000);
    },

    // 停止加载动画
    stopLoadingAnimation() {
      if (this.tipTimer) {
        clearInterval(this.tipTimer);
        this.tipTimer = null;
      }
    },

    // 生成AI推荐
    async generatePlan() {
      if (!this.userInput.trim()) {
        uni.showToast({
          title: '请输入您的旅行想法',
          icon: 'none'
        });
        return;
      }

      const message = this.buildRequestMessage();
      if (!message) return;

      // 检查缓存
      if (this.messageCache[message]) {
        console.log('使用缓存的推荐结果');
        this.travelPlan = this.messageCache[message];
        return;
      }

      this.loading = true;
      this.error = '';
      this.startLoadingAnimation();

      try {
        const response = await getAiResponse(message);

        if (response.success) {
          this.travelPlan = response.data;

          // 提取城市和日期信息
          const cityMatch = this.userInput.match(/去(.+?)(?:玩|旅游|游玩|游览)/);
          const dateMatch = this.userInput.match(/(\d{1,2}月\d{1,2}日)(?:至|到)(\d{1,2}月\d{1,2}日)/);

          // 保存路线数据时优化城市和日期信息
          const routeData = {
            title: this.travelPlan.split('\n')[0] || '自定义旅行计划',
            city: cityMatch ? cityMatch[1].trim() : '',
            dateRange: dateMatch ? `${dateMatch[1]}至${dateMatch[2]}` : '',
            attractions: this.extractAttractions(this.travelPlan),
            timestamp: new Date().getTime()
          };

          // 存入本地存储
          uni.setStorageSync('travelRouteData', JSON.stringify(routeData));

          // 存入缓存
          this.messageCache[message] = this.travelPlan;

          // 更新本地存储
          this.saveCache(this.messageCache);
        } else {
          this.error = response.error || '获取推荐失败';
          uni.showToast({
            title: this.error,
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('生成攻略失败:', error);
        this.error = '网络错误，请稍后重试';
        uni.showToast({
          title: this.error,
          icon: 'none'
        });
      } finally {
        this.loading = false;
        this.stopLoadingAnimation();
      }
    },

    // 保存缓存
    saveCache(cache) {
      try {
        const cacheData = {
          data: cache,
          timestamp: new Date().getTime()
        };
        uni.setStorageSync('customTravelCache', JSON.stringify(cacheData));
      } catch (e) {
        console.error('保存缓存失败:', e);
      }
    },

    // 保存为行程
    async saveToPlan() {
      if (!this.travelPlan) {
        uni.showToast({
          title: '暂无可保存的行程内容',
          icon: 'none'
        });
        return;
      }

      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo || !userInfo.id) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      try {
        // 生成计划标题
        const planTitle = `自定义旅行计划-${new Date().toLocaleDateString()}`;

        // 检查是否存在同名行程
        const existingPlans = await getUserTravelPlans(userInfo.id);
        const existingPlan = existingPlans.data.find(plan => plan.planName === planTitle);

        if (existingPlan) {
          uni.showModal({
            title: '提示',
            content: '已存在同名行程，请选择操作',
            showCancel: true,
            cancelText: '新增',
            confirmText: '覆盖',
            success: async (res) => {
              if (res.confirm) {
                // 覆盖现有行程
                await updateTravelPlan(existingPlan.id, {
                  planName: planTitle,
                  travelPlan: this.travelPlan,
                  userId: userInfo.id
                });
                uni.showToast({
                  title: '行程已更新',
                  icon: 'success'
                });
              } else {
                // 创建新行程
                const newTitle = `${planTitle}(${existingPlans.data.filter(p => p.planName.startsWith(planTitle)).length + 1})`;
                await createTravelPlan({
                  planName: newTitle,
                  travelPlan: this.travelPlan,
                  userId: userInfo.id
                });
                uni.showToast({
                  title: '新行程已创建',
                  icon: 'success'
                });
              }
            }
          });
        } else {
          // 直接创建新行程
          await createTravelPlan({
            planName: planTitle,
            travelPlan: this.travelPlan,
            userId: userInfo.id
          });
          uni.showToast({
            title: '行程已保存',
            icon: 'success'
          });
        }
      } catch (err) {
        console.error('保存行程失败:', err);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      }
    },

    // 查看路线地图
    async viewRouteMap() {
      if (!this.travelPlan) {
        uni.showToast({
          title: '暂无可查看的路线',
          icon: 'none'
        });
        return;
      }

      // 显示生成中动画
      uni.showLoading({
        title: '路线生成中...',
        mask: true
      });

      // 使用AI接口获取景点信息
      const message = this.travelPlan + '根据上述信息帮我提取景点名称';
      const aidata = await getAiResponse(message);
      
      // 隐藏加载动画
      uni.hideLoading();
      
      if (!aidata.success || !aidata.data) {
        uni.showToast({
          title: '提取景点失败',
          icon: 'none'
        });
        return;
      }
      
      // 解析AI返回的景点数据
      const attractions = aidata.data.split('\n')
        .filter(line => line.trim() && line.startsWith('-'))
        .map(line => ({
          name: line.replace('-', '').trim(),
          description: '景点'
        }));

      if (attractions.length === 0) {
        uni.showToast({
          title: '未找到景点信息',
          icon: 'none'
        });
        return;
      }

      // 从行程内容中提取城市名称
      let city = '';
      const cityMatch = this.userInput.match(/去(.+?)(?:玩|旅游|游玩|游览)/);
      if (cityMatch) {
        city = cityMatch[1].trim();
      } else {
        // 如果输入中没有找到城市名，尝试从内容中提取
        const contentCityMatch = this.travelPlan.match(/([^市县区]+)[市县区]/);
        if (contentCityMatch) {
          city = contentCityMatch[1];
        }
      }
      
      // 如果都没找到，使用默认值
      if (!city) {
        city = '杭州';
      }

      // 提取日期范围
      let dateRange = '';
      const dateMatch = this.userInput.match(/(\d{1,2}月\d{1,2}日)(?:至|到)(\d{1,2}月\d{1,2}日)/);
      if (dateMatch) {
        dateRange = `${dateMatch[1]}至${dateMatch[2]}`;
      }

      // 构建路线数据
      const routeData = {
        city: city,
        title: this.travelPlan.split('\n')[0] || '自定义旅行路线',
        dateRange: dateRange || '暂无日期',
        attractions: attractions,
        timestamp: new Date().getTime()
      };

      try {
        uni.setStorageSync('travelRouteData', JSON.stringify(routeData));
        uni.navigateTo({
          url: '/package-discovery/pages/AI-travel'
        });
      } catch (e) {
        console.error('保存路线数据失败:', e);
        uni.showToast({
          title: '路线生成失败',
          icon: 'none'
        });
      }
    },

    // 提取景点信息
    extractAttractions(travelPlan) {
      const attractions = [];
      const lines = travelPlan.split('\n');
      let currentDay = '';
      let currentDescription = '';

      for (let line of lines) {
        // 匹配日期标题
        const dayMatch = line.match(/第([一二三四五六七八九十\d]+)[天日]：(.+)/);
        if (dayMatch) {
          currentDay = `第${dayMatch[1]}天`;
          currentDescription = dayMatch[2];
          attractions.push({
            name: line.trim(),
            dayTitle: currentDay,
            timeSlot: '全天',
            description: currentDescription
          });
          continue;
        }

        // 匹配具体景点
        const timeMatch = line.match(/([上中下晚]午|早晨|傍晚|晚上)[:：](.+)/);
        if (timeMatch && currentDay) {
          const timeSlot = timeMatch[1];
          const content = timeMatch[2].trim();

          // 提取景点名称
          const spotMatches = content.match(/[【\[](.*?)[】\]]|(?:游览|参观|前往|到达)([^，。；]+)/g);
          if (spotMatches) {
            spotMatches.forEach(spot => {
              const spotName = spot.replace(/[【\[\]】]|(?:游览|参观|前往|到达)/, '').trim();
              if (spotName && spotName.length >= 2) {
                attractions.push({
                  name: spotName,
                  dayTitle: currentDay,
                  timeSlot: timeSlot,
                  description: content
                });
              }
            });
          }
        }
      }

      return attractions;
    }
  },

  mounted() {
    // 尝试加载缓存
    try {
      const cachedData = uni.getStorageSync('customTravelCache');
      if (cachedData) {
        const parsedCache = JSON.parse(cachedData);
        const now = new Date().getTime();
        // 检查缓存是否在3小时内
        if (now - parsedCache.timestamp < 3 * 60 * 60 * 1000) {
          this.messageCache = parsedCache.data;
        } else {
          // 清除过期缓存
          uni.removeStorageSync('customTravelCache');
        }
      }
    } catch (e) {
      console.error('加载缓存失败:', e);
    }
  },
  beforeDestroy() {
    // 清理定时器
    this.stopLoadingAnimation();
  }
}
</script>

<style lang="scss">
.customize-travel {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20rpx;
  box-sizing: border-box;
  position: relative;
  width: 100%;

  .chat-section {
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2rpx);
      box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.12);
    }

    .chat-input {
      width: 100%;
      height: 240rpx;
      padding: 24rpx;
      font-size: 30rpx;
      line-height: 1.6;
      border: 2rpx solid #e0e0e0;
      border-radius: 16rpx;
      box-sizing: border-box;
      margin-bottom: 24rpx;
      transition: all 0.3s ease;

      &:focus {
        border-color: #4CAF50;
        box-shadow: 0 0 0 4rpx rgba(76, 175, 80, 0.1);
      }
    }

    .send-btn {
      background: linear-gradient(135deg, #4CAF50, #388E3C);
      color: #fff;
      border: none;
      border-radius: 40rpx;
      padding: 20rpx 40rpx;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.3);
      transition: all 0.3s ease;

      .icon {
        margin-right: 12rpx;
        font-size: 36rpx;
      }

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.2);
      }

      &:disabled {
        opacity: 0.7;
        background: #ccc;
        box-shadow: none;
      }
    }
  }

  .loading-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border-radius: 20rpx;
    margin: 30rpx 0;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    padding: 40rpx;

    .loading-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 40rpx;
    }

    .loading-spinner {
      display: flex;
      margin-bottom: 40rpx;

      .spinner-circle {
        width: 24rpx;
        height: 24rpx;
        background: #4CAF50;
        border-radius: 50%;
        margin: 0 10rpx;
        animation: bounce 1.4s infinite ease-in-out;

        &:nth-child(1) {
          animation-delay: -0.32s;
        }

        &:nth-child(2) {
          animation-delay: -0.16s;
        }
      }
    }

    .loading-text {
      text-align: center;

      .title {
        display: block;
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
      }

      .subtitle {
        display: block;
        font-size: 30rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }

  .plan-section {
    flex: 1;
    background: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    margin: 30rpx;
    margin-bottom: 140rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    box-sizing: border-box;
    width: calc(100% - 60rpx);

    .plan-content {
      font-size: 30rpx;
      line-height: 1.8;
      color: #666;
      padding: 0 20rpx;

      .plan-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 40rpx;
        padding-bottom: 30rpx;
        border-bottom: 2rpx solid #f0f0f0;
        text-align: center;
      }

      rich-text {
        width: 100%;
        display: block;
        word-break: break-all;
        word-wrap: break-word;
        white-space: pre-wrap;
      }
    }
  }

  .bottom-buttons {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    padding: 30rpx 40rpx;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20rpx);
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 100;

    button {
      flex: 1;
      margin: 0 20rpx;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 44rpx;
      font-size: 30rpx;
      font-weight: 500;
      transition: all 0.3s ease;

      .icon {
        margin-right: 12rpx;
        font-size: 36rpx;
      }

      &:active {
        transform: scale(0.98);
      }
    }

    .route-map-btn {
      background: #f5f5f5;
      color: #666;
      border: 2rpx solid #e0e0e0;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

      &:active {
        background: #e8e8e8;
      }
    }

    .save-plan-btn {
      background: linear-gradient(135deg, #4CAF50, #388E3C);
      color: #fff;
      border: none;
      box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.3);

      &:active {
        background: linear-gradient(135deg, #388E3C, #2E7D32);
      }
    }
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1.0);
  }
}

// 响应式适配
@media screen and (max-width: 375px) {
  .customize-travel {
    padding: 16rpx;

    .chat-section {
      padding: 24rpx;

      .chat-input {
        height: 200rpx;
        font-size: 28rpx;
      }

      .send-btn {
        padding: 16rpx 32rpx;
        font-size: 28rpx;
      }
    }

    .plan-section {
      padding: 30rpx;
      margin: 20rpx;
      margin-bottom: 120rpx;

      .plan-content {
        font-size: 28rpx;

        .plan-title {
          font-size: 32rpx;
        }
      }
    }

    .bottom-buttons {
      padding: 20rpx 30rpx;

      button {
        height: 80rpx;
        font-size: 28rpx;
      }
    }
  }
}

@media screen and (min-width: 768px) {
  .customize-travel {
    max-width: 750rpx;
    margin: 0 auto;
    padding: 30rpx;

    .chat-section {
      padding: 40rpx;

      .chat-input {
        height: 280rpx;
        font-size: 32rpx;
      }

      .send-btn {
        padding: 24rpx 48rpx;
        font-size: 32rpx;
      }
    }

    .plan-section {
      padding: 50rpx;
      margin: 40rpx;
      margin-bottom: 160rpx;

      .plan-content {
        font-size: 32rpx;

        .plan-title {
          font-size: 40rpx;
        }
      }
    }

    .bottom-buttons {
      padding: 40rpx 50rpx;

      button {
        height: 96rpx;
        font-size: 32rpx;
      }
    }
  }
}
</style>
